﻿using System;
using System.Collections.Generic;
using System.Text;

namespace OL.FrameCore.Infrastructure.Security
{
    /// <summary>
    /// RSA加密解密帮助
    /// </summary>
    public class RSAHelper
    {
        static object obj = new object();
        static RsaKeyPair CacheRsaKey;
        static DateTime KeyTime;

        /// <summary>
        /// 获取公钥
        /// </summary>
        /// <returns></returns>
        public static string GetPublic()
        {
            if (CacheRsaKey == null || KeyTime == null || DateTime.Now.Date > KeyTime.Date)
            {
                lock (obj)
                {
                    //新密钥
                    var rsaKeyPair = RSAUtility.CreateKeyPair();
                    CacheRsaKey = new RsaKeyPair
                    {
                        PublicKey = rsaKeyPair.Item1,
                        PrivateKey = rsaKeyPair.Item2
                    };
                    KeyTime = DateTime.Now;
                }
            }

            if (CacheRsaKey == null)
            {
                throw new Exception("密钥生成失败");
            }
            else
            {
                return CacheRsaKey.PublicKey;
            }
        }

        /// <summary>
        /// 获取私钥
        /// </summary>
        /// <returns></returns>
        public static string GetPrivate()
        {
            if (CacheRsaKey == null)
            {
                throw new Exception("密钥未生成");
            }
            else
            {
                return CacheRsaKey.PrivateKey;
            }
        }

        /// <summary>
        /// 用当前密钥解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DecryptRSA(string str)
        {
            var privateKey = GetPrivate();
            return RSAUtility.Decrypt(privateKey, str);
        }
    }

    /// <summary>
    /// 公私秘钥
    /// </summary>
    public class RsaKeyPair
    {
        /// <summary>
        /// 公钥
        /// </summary>
        public string PublicKey { get; set; }
        /// <summary>
        /// 秘钥
        /// </summary>
        public string PrivateKey { get; set; }
    }
}
